# -*- coding: utf-8 -*-

from marshmallow import Schema, fields

from odoo import models


BaseSchema = Schema


class MetaModel(models.MetaModel):
    def __init__(cls, name, bases, attrs):
        super().__init__(name, bases, attrs)

        schema_attrs = {}
        for key, attr in attrs.items():
            if isinstance(attr, models.Field):
                schema_field_type = field_type_mapping.get(attr.__class__.__name__)
                if schema_field_type:
                    schema_attrs[key] = schema_field_type()
        if schema_attrs:
            schema_cls_name = '{}Schema'.format(name)
            cls.schema_cls = type(schema_cls_name, (BaseSchema, ), schema_attrs)


class SchemaModel(models.AbstractModel, metaclass=MetaModel):
    _auto = True
    _register = False
    _abstract = False
    _transient = False


field_type_mapping = {
    'Boolean': fields.Boolean,
    'Integer': fields.Integer,
    'Float': fields.Float,
    'Char': fields.Str,
    'Text': fields.Str,
    'Html': fields.Str,
    'Date': fields.Date,
    'Datetime': fields.DateTime,
}
